package nuist.hanniko.stu.webbackend.controller.api;

import io.jsonwebtoken.Claims;
import nuist.hanniko.stu.webbackend.dao.mapper.NotificationMapper;
import nuist.hanniko.stu.webbackend.model.Notification;
import nuist.hanniko.stu.webbackend.util.ResponseData;
import nuist.hanniko.stu.webbackend.util.TokenHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("api/notification")
public class NotificationController {

    private final NotificationMapper notificationMapper;

    @Autowired
    public NotificationController(NotificationMapper notificationMapper) {
        this.notificationMapper = notificationMapper;
    }

    @PostMapping("confirm")
    @ResponseBody
    public ResponseData confirm(@RequestParam(name = "id") String[] id) {
        ResponseData responseData = new ResponseData();

        if (notificationMapper.confirmBatch(Arrays.asList(id)) == 0) {
            responseData.setMessage("FAILURE");
            responseData.setStatus(false);
        } else {
            responseData.setMessage("SUCCESS");
            responseData.setStatus(true);
        }

        return responseData;
    }

    @GetMapping("getUnconfirmed")
    @ResponseBody
    public ResponseData getUnconfirmed(@RequestHeader(value = "X-Token") String token) {
        ResponseData responseData = new ResponseData();

        Claims claims = TokenHelper.extractJwt(token);

        if (claims == null) {
            responseData.setMessage("FAILURE");
            responseData.setStatus(false);
        } else {
            List<Notification> notifications = notificationMapper.getAllUnconfirmedByUid((String) claims.get("uid"));
            responseData.setStatus(true);
            responseData.setMessage("SUCCESS");
            responseData.setData(notifications);
        }

        return responseData;
    }

    @GetMapping("getAll")
    @ResponseBody
    public ResponseData getAll(@RequestHeader(value = "X-Token") String token) {
        ResponseData responseData = new ResponseData();

        Claims claims = TokenHelper.extractJwt(token);

        if (claims == null) {
            responseData.setMessage("FAILURE");
            responseData.setStatus(false);
        } else {
            List<Notification> notifications = notificationMapper.getAllByUid((String) claims.get("uid"));
            responseData.setStatus(true);
            responseData.setMessage("SUCCESS");
            responseData.setData(notifications);
        }

        return responseData;
    }

}
